package com.zhiyou.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhiyou.pojo.JsonResult;
import com.zhiyou.pojo.User;

public class ReleaseInterceptor extends HandlerInterceptorAdapter {
	// 在执行controller方法之前,执行此方法
	// 返回值:true,放行请求
	// false,拦截请求
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 判断用户是否登录
		// 登录成功在session存user用户对象
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");

		if (user == null) {
			// 用户不存在,未登录
			// 给客户端响应
			JsonResult<String> result = new JsonResult<String>(101, "用户未登录", null);
			// 把对象转换成json字符串
			ObjectMapper mapper = new ObjectMapper();
			String json = mapper.writeValueAsString(result);
			// 把json数据交给客户端(做出响应)
			response.getWriter().write(json);
			// request.getRequestDispatcher("../../WEB-INF/login.jsp").forward(request,
			// response);
			return false;
		} else {
			if (user.getStatus() == 0) {
				JsonResult<String> result = new JsonResult<String>(102, "用户未实名认证", null);
				ObjectMapper mapper = new ObjectMapper();
				String json = mapper.writeValueAsString(result);
				response.getWriter().write(json);
				return false;
			} else if (user.getStatus() == 1) {
				JsonResult<String> result = new JsonResult<String>(103, "实名认证审核中,无法发布项目", null);
				ObjectMapper mapper = new ObjectMapper();
				String json = mapper.writeValueAsString(result);
				response.getWriter().write(json);
				return false;
			}else if (user.getStatus() == 2) {
				JsonResult<String> result = new JsonResult<String>(104, "可以发布", null);
				ObjectMapper mapper = new ObjectMapper();
				String json = mapper.writeValueAsString(result);
				response.getWriter().write(json);
				return false;
			} else if (user.getStatus() == 3) {
				JsonResult<String> result = new JsonResult<String>(105, "实名认证审核失败,点击确定跳转认证界面", null);
				ObjectMapper mapper = new ObjectMapper();
				String json = mapper.writeValueAsString(result);
				response.getWriter().write(json);
				return false;
			} 
			return true;

		}

	}

}
